const express = require("express");
const router = express.Router();
const mongoose = require("mongoose");
const request = require("request");
import * as config from "../../config";
import big from "../../big";

const _ = require("lodash");
import { Request, Response } from "express";
import { NextFunction } from "express-serve-static-core";
import efetch from "../efetch";
import jar from "../toughCookie";

import r from "../r";

const getLoveLists = (symbolLists: any) => {
  const muLists = symbolLists.slice();
  let ret: Array<any> = [];
  for (const key in muLists) {
    if (muLists.hasOwnProperty(key)) {
      const item = muLists[key];
      ret = ret.concat(
        item.lists
          .map((d: any) => {
            return {
              ...d,
              type: "love",
              symbol: `${d.symbol}_${item.symbol}`
            };
          })
          .filter((d: any) => {
            return d.isLove;
          })
      );
    }
  }
  return ret;
};

function formatSymbol(a: any) {
  const ret: any = {};

  let a1 = a.slice();

  a1 = a1.slice().map((d: any) => {
    const [zi, mu] = d.currencyPair.split("_");
    return {
      c: big.toFixed(d.c, config.point),
      change: big.toFixed(d.change, config.point),
      zi,
      mu,
      h: big.toFixed(d.h, config.point),
      l: big.toFixed(d.l, config.point),
      o: big.toFixed(d.o, config.point),
      t: big.toFixed(d.t, config.point),
      v: big.toFixed(d.v, config.point),
      lastPrice: big.toFixed(d.c, config.point),
      isLove: false,
      sort: 1
    };
  });

  a1.forEach((d: any) => {
    if (!ret[d.mu]) {
      ret[d.mu] = {
        lists: [],
        symbol: d.mu
      };
    }
    ret[d.mu].lists.push({
      c: d.c,
      change: d.change,
      symbol: d.zi,
      h: d.h,
      l: d.l,
      o: d.o,
      t: d.t,
      v: d.v,
      lastPrice: d.lastPrice,
      isLove: d.isLove,
      sort: d.sort
    });
  });

  const arr = [];

  for (const key in ret) {
    if (ret.hasOwnProperty(key)) {
      const item = ret[key];
      // item.lists[0].lastPrice = item.lastPrice;
      arr.push(item);
    }
  }

  return arr;
}

router.get("/", async function(
  req: Request,
  res: Response,
  next: NextFunction
) {
  const { coin } = req.query;

  if (process.env.NODE_ENV === "eh") {
    const data = "dslkfjlskdjfsfd";
    res.json({
      code: 200,
      data,
      msg: "success"
    });
  }
  try {
    const newurl = `${config.api}/market/ticker24h`;
    const ret = await r(
      {
        method: "GET",
        url: newurl
      },
      req,
      res
    );
    const jsonRet = JSON.parse(ret.body);

    if (jsonRet && jsonRet.data) {
      jsonRet.data = formatSymbol(jsonRet.data);

      // jsonRet.data.push({
      //   symbol: "love",
      //   lists: getLoveLists(jsonRet.data)
      // });
    } else {
      jsonRet.data = [];
    }
    res.json(jsonRet);
  } catch (e) {
    res.json({
      code: -1,
      data: undefined,
      msg: e
    });
  }

  // const jsonRet: any = Object.assign({}, config.symbol);
  // if (jsonRet && jsonRet.data) {
  //   const ret = [];
  //   for (let key in jsonRet.data) {
  //     const item = jsonRet.data[key];
  //     if (Object.prototype.toString.call(item) === "[object Array]") {
  //       ret.push({
  //         symbol: key,
  //         lists: item.slice().map((d: any) => {
  //           return {
  //             h: d.high24,
  //             l: d.low24,
  //             lastPrice: d.last,
  //             change: d.rate,
  //             symbol: d.market,
  //             v: d.vol24,
  //             sort: d.sort,
  //             isLove: d.collect
  //           };
  //         })
  //       });
  //     }
  //   }
  //   ret.push({
  //     symbol: "love",
  //     lists: getLoveLists(ret)
  //   });
  //   jsonRet.data = ret;
  // } else {
  //   jsonRet.data = [];
  // }
  // res.json(jsonRet);
});

export default router;
